package com.aistar.util;

import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Component
public class QiniuUtil {
    private static final String accessKey = "2SYbWpEdgeua9QiwLEBVoy4EmA9-9-haL8p99f5o";
    private static final String secretKey = "I7T1NKIOeTjQzHP4ZSUukzsUiPdtWV8KK4QqHvVC";
    private static final String bucket = "study-project";
    private static final String domain = "http://qad2oc1j2.bkt.clouddn.com/";

    /**
     * 提取文件后缀，将文件名改为UUID
     *
     * @param oldName 原文件名
     * @return 修改后的文件名
     */
    private static String getNewName(String oldName) {
        String[] temp = oldName.split("\\.");
        String type = temp[temp.length - 1]; // 获得最后一个.后面的字符
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return uuid + "." + type;
    }

    /**
     * 对外上传
     *
     * @param file 文件对象
     * @return 上传后图片路径URL
     */
    public static String upload(MultipartFile file) {
        String token = Auth.create(accessKey, secretKey).uploadToken(bucket);
        UploadManager uploadManager = new UploadManager(new Configuration(Region.autoRegion()));
        try {
            if (file.getOriginalFilename() != null) {
                String fileName = getNewName(file.getOriginalFilename());
                Response response = uploadManager.put(file.getInputStream(), fileName, token, null, null);
                String url = (String) response.jsonToMap().get("key");
                return domain + url;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
